package com.it.util;

import com.it.pojo.book;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class HtmlParseUtil {
    static int i;
    static Random r = new Random();

    /**
     * 爬取京东页面的工具类
     *
     * @param keywords
     * @return
     */
    public static List<book> HTmlJdUtil(String keywords, int page) {
        List<book> books = new ArrayList<>();
        //获取请求
        String url = "https://search.jd.com/Search?keyword=" + keywords + "&page=" + page;
        //解析网页
        Document parse = null;
        try {
            /**
             * 参数一:解析的URL地址
             * 参数二:get请求的超时为60秒
             */
            parse = Jsoup.parse(new URL(url), 60000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //加载图书列表
        Element j_crumbsBar = parse.getElementById("J_goodsList");
        //包含多个标签
        Elements li = j_crumbsBar.getElementsByTag("li");
        for (Element element : li) {
            //获取书名
            String bookName = element.select("div.p-name > a > em").text();
            //获取价格
            String text4 = element.select("div.p-price > strong > i").text();
            double price = Double.parseDouble(text4);
            /*//获取销量
            //使用正则表达式(\\d)表示数字字符,+表示匹配一个或多个数字字符
            Pattern compile = Pattern.compile("(\\d+)");
            String SalesVolume = element.select("div.p-commit > strong > a").text().replaceAll("[^\\d]", "");
            Matcher matcher = compile.matcher(SalesVolume);
            //Matcher 对象的 find()表示是否存在该匹配模式
            while (matcher.find()) {
                //Integer i = Integer.parseInt(matcher.group(1));
                if (matcher.group(1).length() <= 3) {
                    i = Integer.parseInt(matcher.group(0));
                    i *= 10000;
                } else {
                    i = Integer.parseInt(matcher.group(0));
                }
            }*/
            //封装
            book book = new book(bookName, price, RandomValue(), RandomInventory(),keywords);
            books.add(book);
        }
        return books;
    }

    /**
     * 随机销量
     *
     * @return
     */
    public static int RandomValue() {
        return 100 + r.nextInt(1000);
    }

    /**
     * 随机的库存数据
     *
     * @return
     */
    public static int RandomInventory() {
        return r.nextInt(50000) + 6000;
    }
}
